#include "soci/oracle/soci-oracle.h"
#include "soci/soci.h"
#include "soci/rowset.h"

#include <iostream>
#include <string>
#include <cstring>
#include <ctime>

using namespace soci;
using namespace std;

//std::string connect_str = "service=orcl user=aistor password=aistor";
std::string connect_str = "user=aistor password=aistor";
backend_factory const &backEnd = *soci::factory_oracle ();

int main ()
{
    soci::session sql (backEnd, connect_str);
    std::cout << "hello" << std::endl;
    std::time_t now = std::time (NULL);
    std::tm t1, t2;
    t2 = *std::localtime (&now);

    sql << "select t from (select :t as t from dual)",
        into (t1), use (t2);

    char buf[25];
    strftime (buf, sizeof (buf), "%m-%d-%Y %H:%M:%S", &t2);
    std::cout << buf << std::endl;

    int row_cnt = -1;
    sql << "select count(*) from fat", into (row_cnt);
    std::cout << "count for fat: " << row_cnt << std::endl;


    /*
    vector<int> ids;
    vector<string> names;

    for (int i = 0; i != 10; ++i)
    {
        ids.push_back(i);
        names.push_back("abcd");
    }

    sql << "insert into fat(disc_no, checksum) values(:id, :name)",
            use(ids), use(names);

    */

    /*
    int cnt = 0;
    sql << "select count(*) from fat", into(cnt);

    vector<string> names(cnt);
    vector<indicator> ids;
    cout << names.size() << endl;
    sql << "select checksum from fat", into(names, ids);
    cout << names.size() << endl;
    */


    /*
    soci::rowset<soci::row> rs = sql.prepare << "select * from fat";

    for (soci::rowset<soci::row>::iterator it = rs.begin (); it != rs.end (); it ++)
    {
        //遇到字段为空的时候就会出错
        //std::cout << "checksum: " << (*it).get<std::string>("CHECKSUM");
        //std::cout << "checksum: " << it->get<long long>(0) << std::endl;

        std::cout << "ID: " << it->get<long long> ("ID") << std::endl;
        string tmp = "";

        try
        {
            tmp =  it->get<string> ("CHECKSUM");
        }
        catch (const soci::soci_error &e)
        {
            cout << "err:" << e.what () << endl;
        }
        std::cout << "checksum: " << tmp << std::endl;
        cnt ++;
    }
    */

    /*
     * 手动保证字符串字段不为空!
    soci::rowset<string> rs = sql.prepare << "select checksum from fat";
    for (soci::rowset<string>::iterator it = rs.begin (); it != rs.end (); it ++)
    {
        string tmp = "";
        try
        {
            string tmp = (*it);
        }
         catch (const soci::soci_error &e)
        {
            cout << "err:" << e.what () << endl;
        }

        std::cout << "checksum: " << tmp << std::endl;
    }
    */

    /// 必须保证数据库中相关记录无NULL
    /// 可以在创建数据库时确保相关字段非NULL
    soci::rowset<int> rs = sql.prepare << "select disc_no from fat";
    for (soci::rowset<int>::iterator it = rs.begin (); it != rs.end (); it ++)
    {
        std::cout << "disc_no: " << *it << std::endl;
    }

    return 0;
}
